package com.sky.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author 自然醒
 * @version 1.0
 */
@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.insertDish(dish);
        Long dishId = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if( flavors != null && !flavors.isEmpty()){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
        }
        dishMapper.insertDishFlavor(flavors);
    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> dishes = dishMapper.search(dishPageQueryDTO);
        List<DishVO> records = dishes.getResult();
        Long total = dishes.getTotal();
        return new PageResult(total,records);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(List<Long> ids) {
        List<DishVO> dishVOS = new ArrayList<>();
        ids.forEach(id -> {
            dishVOS.add(dishMapper.getById(id));
        });
        dishVOS.forEach(dishVO -> {
            if(dishVO.getStatus() == StatusConstant.ENABLE){
                throw new RuntimeException(MessageConstant.DISH_ON_SALE);
            }
        });
        dishVOS.forEach(dishVO -> {
            if(setmealDishMapper.selectIsRelatedWithSetmeal(dishVO.getId())!=null
            && !setmealDishMapper.selectIsRelatedWithSetmeal(dishVO.getId()).isEmpty()){
                throw new RuntimeException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        });
        dishMapper.deleteById(ids);
        dishMapper.deleteDishFlavorByDishId(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DishVO getById(Long id) {
        DishVO dishVO = dishMapper.getById(id);
        dishVO.setFlavors(dishMapper.getByDishId(id));
        return dishVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.updateDish(dish);
        dishMapper.deleteDishFlavorByDishId(Collections.singletonList(dishDTO.getId()));
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if( flavors != null && !flavors.isEmpty()){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
        }
        dishMapper.insertDishFlavor(flavors);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder().id(id).status(status).build();
        dishMapper.updateDish(dish);
        if(status == StatusConstant.DISABLE){
            List<SetmealDish> setmealDishes = setmealDishMapper.selectIsRelatedWithSetmeal(id);
            List<Long> dishIds = new ArrayList<>();
            if(setmealDishes != null && !setmealDishes.isEmpty()){
                setmealDishes.forEach(setmealDish -> {
                    dishIds.add(setmealDish.getDishId());
                });
                dishIds.forEach(dishId -> {
                    Setmeal setmeal = Setmeal.builder().id(dishId).status(status).build();
                    setmealMapper.update(setmeal);
                });
            }
        }
    }

    @Override
    public List<Dish> searchDishByCategoryId(Long categoryId) {
       Dish dish = Dish.builder()
               .categoryId(categoryId)
               .status(StatusConstant.ENABLE)
               .build();
       return dishMapper.list(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
